package com.cheifsteam.springframework.beans.factory.support;

import com.cheifsteam.springframework.beans.BeansException;
import com.cheifsteam.springframework.beans.factory.FactoryBean;
import com.cheifsteam.springframework.beans.factory.config.BeanDefinition;
import com.cheifsteam.springframework.beans.factory.config.BeanPostProcessor;
import com.cheifsteam.springframework.beans.factory.config.ConfigurableBeanFactory;
import com.cheifsteam.springframework.utils.ClassUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 屈燃希
 * @date 2025/1/18 22:52
 * @content
 */
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {



    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    private  final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    @Override
    public Object getBean(String name) {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    private <T> T doGetBean(String name, Object[] args) {
        Object sharedInstance = getSingleton(name);
        if (sharedInstance != null) {
            return (T) getObjectForBeanInstance(sharedInstance, name);
        }
        BeanDefinition beanDefinition = getBeanDefinition(name);
        Object bean = (T) createBean(name, beanDefinition, args);
        return  (T) getObjectForBeanInstance(bean, name);
    }
    private Object getObjectForBeanInstance(Object beanInstance, String beanName) {
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        Object object = getCachedObjectForFactoryBean(beanName);

        if (object == null) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }

        return object;
    }
    protected abstract BeanDefinition getBeanDefinition(String beanName);
    protected abstract Object createBean(String name, BeanDefinition beanDefinition,Object[] args);


    public List<BeanPostProcessor> getBeanPostProcessors(){
        return this.beanPostProcessors;
    }
    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public ClassLoader getBeanClassLoader() {
        return beanClassLoader;
    }
}
